package com.paranoid;

import com.paranoid.realm.CustomerMd5Realm;
import javafx.scene.shape.Shape3D;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;
import org.junit.Test;

import java.lang.reflect.Array;
import java.util.Arrays;

public class Md5SaltHash {

    @Test
    public void test(){

        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();

        CustomerMd5Realm realm = new CustomerMd5Realm();

        //设置realm使用hash凭证匹配器
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        //设置md5加密方式
        credentialsMatcher.setHashAlgorithmName("md5");
        //设置hash散列的次数
        credentialsMatcher.setHashIterations(1024);
        realm.setCredentialsMatcher(credentialsMatcher);

        defaultSecurityManager.setRealm(realm);

        SecurityUtils.setSecurityManager(defaultSecurityManager);

        Subject subject = SecurityUtils.getSubject();

        UsernamePasswordToken token = new UsernamePasswordToken("jay","123");

        try {
            subject.login(token);
            System.out.println("登录成功");
            System.out.println(subject.isAuthenticated());
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("密码错误");
        }

        //授权
        if(subject.isAuthenticated()){
            //基于角色的权限控制
            System.out.println(subject.hasRole("jay"));
            //基于多角色的权限控制
            System.out.println(subject.hasAllRoles(Arrays.asList("admin", "user")));

            //是否具有其中一个角色
            boolean[] admins = subject.hasRoles(Arrays.asList("admin","user","jay"));
            for (boolean admin : admins) {
                System.out.println(admin);
            }
            System.out.println("==============");
            //基于权限字符串的访问控制   资源标识符：操作：资源类型
            System.out.println(subject.isPermitted("user:update:*"));
            System.out.println(subject.isPermitted("product:create:02"));

            //分别具有哪些权限    返回值为boolean类型集合
            boolean[] permitted = subject.isPermitted("user:*:01", "product:create:03");
            for (boolean b : permitted) {
                System.out.println(b);
            }

            //同时具有哪些权限    返回值为单个boolean
            System.out.println(subject.isPermittedAll("user:*:09", "product:create:05"));

        }




    }


}
